package org.example.me.handler;

import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import org.example.me.enums.ExcelTypeEnum;
import org.example.me.handler.template.AbstractCommonExportTemplate;
import org.example.me.handler.context.ExcelContextExtend;
import org.example.me.handler.context.FileContext;
import org.example.me.handler.context.SheetCreator;
import org.example.me.dao.DataGenerator;
import org.example.me.model.Order;
import org.example.me.model.User;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 多文件Excel导出处理器
 * 负责将数据导出为多个Excel文件
 */
@Slf4j
@Component
public class MultiFileExportHandler extends AbstractCommonExportTemplate {

    /**
     * 获取处理器对应的Excel类型
     *
     * @return Excel类型枚举值
     */
    @Override
    public ExcelTypeEnum getExcelType() {
        return ExcelTypeEnum.MULTI_FILE;
    }

    /**
     * 导出多文件数据
     *
     * @param excelContext Excel上下文信息
     */
    @Override
    protected void export(ExcelContextExtend excelContext) {
        // 初始化用户导出临时目录
        List<Order> orders = DataGenerator.generateOrderData();
        List<User> users = DataGenerator.generateUserData();

        // 写法1：使用doWriteData方法自动管理文件和Sheet
        doWriteData(excelContext, "文件1", users, SheetCreator.builder().sheetName("用户").tClass(User.class).build());
        doWriteData(excelContext, "文件1", orders, SheetCreator.builder().sheetName("订单").tClass(Order.class).build());
        doWriteData(excelContext, "文件2", orders, SheetCreator.builder().sheetName("订单").tClass(Order.class).build());

        // 写法2：手动管理文件和Sheet
        FileContext fileContext = initFileContext(excelContext.getExcelContext(), "文件3");
        excelContext.addFileContext(fileContext);
        WriteSheet writeSheet = initWriteSheet(SheetCreator.builder().sheetNo(0).sheetName("订单").tClass(Order.class).build());
        WriteSheet writeSheet2 = initWriteSheet(SheetCreator.builder().sheetNo(1).sheetName("用户").tClass(User.class).build());
        fileContext.addWriteSheet(writeSheet);
        fileContext.addWriteSheet(writeSheet2);

        FileContext fileContext2 = initFileContext(excelContext.getExcelContext(), "文件4");
        excelContext.addFileContext(fileContext2);
        WriteSheet writeSheet3 = initWriteSheet(SheetCreator.builder().tClass(Order.class).sheetNo(0).sheetName("订单").build());
        fileContext2.addWriteSheet(writeSheet3);

        doWriteData(fileContext, "用户", users);
        doWriteData(fileContext, "订单", orders);
        doWriteData(fileContext2, "订单", orders);
    }
}